package tech.chuangxiang.weichuangxin;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
    public static final int SHOW_RESPONSE = 0;
    public  String pagenum;
    public boolean is_end;
    public int p_num;
    private Button btn_back;
    private Button btn_home;
    private Button btn_forword;
    private Button btn_pageinfo;
    public ProgressBar jdt;
    private Handler handlernews = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE:
                    String response = (String) msg.obj;
                    Log.d("TAG", response);
                    parseJSONWithJSONObject(response);

            }
        }

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("微创新-他山之石");

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        jdt=(ProgressBar) findViewById(R.id.progressBar);
//        if(jdt.getVisibility() == View.GONE){
//            jdt.setVisibility(View.VISIBLE);
//        }
        p_num=1;
        pagenum="1";
        is_end=false;

        //获取新闻资讯
        get_newsinfo();
        jdt.setVisibility(View.GONE);
        btn_back = (Button) findViewById(R.id.btn_back);
        btn_home = (Button) findViewById(R.id.btn_home);
        btn_forword = (Button) findViewById(R.id.btn_forword);
        btn_pageinfo = (Button) findViewById(R.id.btn_pageinfo);
        btn_pageinfo.setText("No."+pagenum);

        btn_back.setOnClickListener(this);
        btn_home.setOnClickListener(this);
        btn_forword.setOnClickListener(this);



    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_login) {
            TextView name_info = (TextView) findViewById(R.id.wcx_menu);
            name_info.setText("齐威王");
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onClick(View v) {
        if(jdt.getVisibility() == View.GONE){
            jdt.setVisibility(View.VISIBLE);
        }

        switch (v.getId()){
            case R.id.btn_back:
                if(p_num > 0){
                    p_num=p_num-1;
                }else{
                    p_num=1;
                }
                if(p_num==0){
                    p_num=1;
                }
                pagenum=String.valueOf(p_num);

                get_newsinfo();
                Log.d("TAG", pagenum);
                break;
            case R.id.btn_home:
                p_num=1;
                pagenum="1";
                get_newsinfo();
                Log.d("TAG", pagenum);
                break;

            case  R.id.btn_forword:
                if(!is_end){

                    Log.d("TAG", pagenum);
                    p_num=p_num+1;
                    pagenum=String.valueOf(p_num);
                    get_newsinfo();
                    Log.d("TAG", pagenum);
                }
                Log.d("TAG", "已经最后一页了");
                break;
            default:
                break;
        }
        jdt.setVisibility(View.GONE);
    }

    private void get_newsinfo() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {



                    URL url = new URL("http://nextbig.net/Api/json_api/p/"+pagenum);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    // 下面对获取到的输入流进行读取
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    // 将服务器返回的结果存放到Message中
                    message.obj = response.toString();
                    handlernews.sendMessage(message);
                    Log.d("TAG", "start");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("TAG", "error");
                    Log.e("TAG",e.getMessage());
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }


//                    if(jdt.getVisibility() == View.VISIBLE){
//                        jdt.setVisibility(View.GONE);
//                    }

                }
            }
        }).start();
    }

    private void parseJSONWithJSONObject(String jsonData) {
        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            ListView list = (ListView)findViewById(R.id.list_news);

            final List<Newslist> news_infos = new ArrayList<Newslist>();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String title = jsonObject.getString("title");
                String url = jsonObject.getString("url");
                String info = jsonObject.getString("body");
                news_infos.add(new Newslist(title, info, url));
                if(url.equals("###")){
                    btn_pageinfo.setText("最后一页");
                    is_end=true;
                }else{
                    btn_pageinfo.setText("No."+pagenum);
                    is_end=false;
                }
            }

            NewslistAdapter adapter = new NewslistAdapter(this, news_infos, R.layout.newslist_row_style);

            list.setAdapter(adapter);
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Newslist ps = news_infos.get(position);
                    //新建一个显式意图，第一个参数为当前Activity类对象，第二个参数为你要打开的Activity类

                    Intent intent =new Intent(MainActivity.this,ShowWebActivity.class);
                    //用Bundle携带数据
                    Bundle bundle=new Bundle();
                    //传递name参数为tinyphp
                    bundle.putString("url", ps.getUrl());
                    // bundle.putString("title", ps.getUrl());
                    intent.putExtras(bundle);

                    startActivity(intent);

                    Log.d("TAG", ps.getUrl());
                    Log.d("TAG","aa");

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
